package com.bjfu.eduservice.controller;


import com.bjfu.common_utils.R;
import com.bjfu.eduservice.client.VodClient;
import com.bjfu.eduservice.entity.EduVideo;
import com.bjfu.eduservice.service.EduVideoService;
import com.bjfu.servicebase.exceptionhandler.GuliException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 课程视频 前端控制器
 * </p>
 *
 * @author Guli
 * @since 2020-07-04
 */
@Api(tags = "小节管理")
@RestController
@RequestMapping("/eduservice/video")
//@CrossOrigin
public class EduVideoController {
    @Autowired
    private VodClient vodClient;

    @Autowired
    private EduVideoService videoService;
    // 添加小节
    @ApiOperation("添加小节")
    @PostMapping("addVideo")
    public R addVideo(@RequestBody EduVideo eduVideo){
        boolean success = videoService.save(eduVideo);
        if(success){
            return R.ok();
        }else {
            return R.error().message("添加失败");
        }
    }

    // 根据小节id查询小节
    @ApiOperation("根据小节id查询")
    @GetMapping("getVideo/{videoId}")
    public R getVideoInfo(
            @PathVariable String videoId
    ){
        EduVideo video = videoService.getById(videoId);
        return R.ok().data("video",video);
    }

    // 修改小节
    @ApiOperation("修改小节")
    @PostMapping("updateVideo")
    public R updateVideo(@RequestBody EduVideo eduVideo){
        boolean success = videoService.updateById(eduVideo);
        if(success){
            return R.ok();
        }else {
            return R.error().message("更新失败");
        }
    }

    // 根据Id删除小节
    // 删除小节的时候，同时把里面视频也删除
    @ApiOperation("删除小节")
    @DeleteMapping("deleteVideo/{videoId}")
    public R deleteVideo(@PathVariable String videoId){
        // 根据小节Id获取视频id，调用该方法删除视频
        EduVideo eduVideo = videoService.getById(videoId);
        String videoSourceId = eduVideo.getVideoSourceId();
        if(!StringUtils.isEmpty(videoSourceId)){
            R r = vodClient.deleteVideo(videoSourceId);
            if(r.getCode() == 20001){
                throw new GuliException(20001,"删除视频失败,熔断器...");
            }
        }
        boolean success = videoService.removeById(videoId);
        if(success){
            return R.ok();
        }else {
            return R.error().message("删除失败");
        }

    }
}

